/**
 * @author 铭
 * @TODO 14/12/2023
 */
package com.woniuxy.service;


import com.woniuxy.daos.TbUserDao;
import com.woniuxy.entitys.TbUser;
import com.woniuxy.utils.LoginUser;
import com.woniuxy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class AuthService {
    @Autowired
    private JWTUtils jwtUtils;
    @Value("${token.jwt.expireTime}")
    private Long expireTime;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TbUserDao tbUserDao;

    public String login(TbUser user){
        String token = jwtUtils.createToken(user.getPhone());
        ValueOperations valueOperations = redisTemplate.opsForValue();
        LoginUser loginUser = new LoginUser();
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * 1000);
        loginUser.setUser(user);
        List<String> userAllPers = tbUserDao.getUserAllPers(user.getPhone());
        loginUser.setUserAllPers(userAllPers);
        valueOperations.set("user:"+user.getPhone(),loginUser,expireTime, TimeUnit.SECONDS);
        return token;
    }
    public boolean isExit(String token){

        if(jwtUtils.verifyToken(token)){
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String username = jwtUtils.getUsername(token);
            LoginUser o = (LoginUser) valueOperations.get("user:" + username);
            if(o!=null){
                verifyToekn(o);
                return  true;
            }
        }
        return  false;
    }

    private void verifyToekn(LoginUser loginUser) {
        long now = System.currentTimeMillis();//当前时间对应的毫秒数
        Long expireTime = loginUser.getExpireTime();
        if(expireTime-now<=60*1000){
            refreshToken(loginUser);
        }
    }

    private void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(System.currentTimeMillis()+expireTime*1000);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("user:"+loginUser.getUser().getPhone(),loginUser,expireTime,TimeUnit.SECONDS);
    }

    public void remove(String token) {
        String username = jwtUtils.getUsername(token);
        redisTemplate.delete("user:"+username);
    }
}
